<template>
  <Top :loading="loading" @click="topHandler" />
  <div v-loading="loading" class="editor">
    <Left class="left" />
    <Center ref="wrapper" class="center" />
    <Right class="right" />
  </div>
</template>

<script lang="ts" setup>
  import Left from '@/views/mupro/editor/components/left.vue'
  import Center from '@/views/mupro/editor/components/center.vue'
  import Right from '@/views/tag/editor/components/right.vue'
  import Top from '@/views/tag/editor/components/top.vue'
  import { gettemp, pubsave } from '@/api/mupro'
  import { useEleStore } from '@/store/modules/coms'
  import router from '@/router'
  import html2canvas from 'html2canvas'

  const route = useRoute()
  const type = ref('add')
  const { setEditorData, setWidgets, clearWidgets } = useEleStore()
  const { getWidgets, getEditorData } = storeToRefs(useEleStore())
  const loading = ref(false)
  // console.log(router.currentRoute.value.matched[0])
  const init = () => {
    if (route.query && route.query.ID) {
      type.value = 'editor'
      getTemp(route.query.ID)
    } else {
      setEditorData({
        cstCode: '',
        cstName: '',
        lcdType: '04',
        csWidth: 800,
        csHeight: 830,
        x0: 0,
        y0: 0,
        enabled: false,
        companyId: '',
        departmentId: '',
        image: '',
        blockStatus: '',
        parentID: '',
        blockAddColor: '00',
        pathImg: '',
        proNum: 1,
        remark: '',
        bgImg: '',
      })
    }
  }
  // 获取模板数据
  const getTemp = async (id: any) => {
    loading.value = true
    const { data: data } = await gettemp({ id })
    loading.value = false
    const editorData = data.data || {}
    editorData.csHeight = editorData.csHeight - 0 || 300
    editorData.csWidth = editorData.csWidth - 0 || 400
    editorData.x0 = editorData.x0 - 0 || 0
    editorData.y0 = editorData.y0 - 0 || 0
    editorData.proNum = editorData.proNum || 1
    try {
      JSON.parse(editorData.json)
      setWidgets(JSON.parse(editorData.json))
    } catch (e) {
      setWidgets([])
    }
    await setEditorData(editorData)
    console.log(editorData)
  }
  init()

  const topHandler = (type: string) => {
    if (type === 'save') save()
    if (type === 'createImg') createImg()
    if (type === 'clear') clear()
  }

  const save = async () => {
    const editorData = dealData()
    if (!editorData.cstCode) {
      ElMessage({
        message: '请填写编码',
        type: 'error',
      })
      return
    }
    if (!editorData.cstName) {
      ElMessage({
        message: '请填写名称',
        type: 'error',
      })
      return
    }
    if (!editorData.cstName) {
      ElMessage({
        message: '请填写名称',
        type: 'error',
      })
      return
    }
    // console.log(editorData)
    // const { code, message } = await pubsave(editorData)
    // if (code == 200) {
    //   ElMessage({
    //     message: message,
    //     type: 'success',
    //   })
    //   router.back()
    // }
    // 保存模板数据
    loading.value = true
    getCanvas()
      .then(async (data) => {
        editorData.image = data
        const { code, message } = await pubsave(editorData)
        loading.value = false
        if (code == 200) {
          ElMessage({
            message: message,
            type: 'success',
          })
          router.back()
        }
      })
      .catch(() => {
        loading.value = false
      })
  }
  const dealData = () => {
    const editorData = JSON.parse(JSON.stringify(getEditorData.value))
    editorData.csHeight += ''
    editorData.csWidth += ''
    editorData.x0 += ''
    editorData.y0 += ''
    editorData.json = JSON.stringify(getWidgets.value)
    return editorData
  }
  const $baseConfirm = inject('$baseConfirm') as any
  const clear = () => {
    $baseConfirm('确定要清空所有组件吗', '提示', async () => {
      clearWidgets()
    })
  }

  // 生成图片
  const wrapper = ref(null) as any
  const getCanvas = () => {
    return new Promise((resolve) => {
      nextTick(() => {
        html2canvas(wrapper.value.getListWapper().value, {
          logging: false,
          allowTaint: true,
          // scale: 3,
          // scale: window.devicePixelRatio,
          // width: shareContent.clientWidth, //dom 原始宽度
          // height: shareContent.clientHeight,
          scrollY: 0,
          scrollX: 0,
          useCORS: true,
          backgroundColor: '#ffffff',
        }).then(function (canvas: any) {
          const imgUrl = canvas.toDataURL('image/png')
          resolve(imgUrl)
        })
      })
    })
  }
  const createImg = async () => {
    const imgUrl: any = await getCanvas()
    const tempLink: any = document.createElement('a') // 创建一个a标签
    tempLink.style.display = 'none'
    tempLink.href = imgUrl
    tempLink.setAttribute('download', '标签') // 给a标签添加下载属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    document.body.appendChild(tempLink) // 将a标签添加到body当中
    tempLink.click() // 启动下载
    document.body.removeChild(tempLink) // 下载完毕删除a标签
    window.URL.revokeObjectURL(imgUrl)
  }
</script>

<style lang="scss" scoped>
  .editor {
    display: flex;
    overflow: auto;
    padding-top: 0 !important;
    padding: 20px;
    // justify-content: space-between;
  }

  .operation {
    display: flex;
    justify-content: flex-end;
    height: 40px;
    align-items: center;

    .save {
      margin-right: 80px;
    }

    .clear {
      margin-right: 10px;
    }
  }
</style>
